import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import * as QueryFlowAction from '../actions/queryFlow'
import {setNowRouterWfpath} from '../actions/list'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'
import {Synergy} from 'weaPortal';

import {WeaTable} from 'comsRedux'

const WeaTableAction = WeaTable.action;

import {WeaErrorPage,WeaTools} from 'ecCom'

import {
    WeaTab,
    WeaTop,
    WeaSearchGroup,
    WeaRightMenu,
    WeaPopoverHrm,
    WeaLeftRightLayout,
    WeaLeftTree
} from 'ecCom'

import {Button, Form, Modal,message} from 'antd'
const createForm = Form.create;
const FormItem = Form.Item;

import cloneDeep from 'lodash/cloneDeep'
import objectAssign from 'object-assign'

import Immutable from 'immutable'
const is = Immutable.is;
const fromJS = Immutable.fromJS;
const Map = Immutable.Map;

let _this = null;

class QueryFlowResult extends React.Component {
    constructor(props) {
        super(props);
        _this = this;
        this.doInit(this.props);
    }
    doInit(props){
        const {actions, location, fields} = props;
        const queryParams = location.query || {};
        actions.setNowRouterWfpath('queryFlow');
        const fromwhere = queryParams.fromwhere || "queryFlow";
        if(fromwhere === "queryFlow"){  //来源查询流程界面
            const stateParams = location.state;
            actions.coverState(stateParams);
        }else{
            actions.initCondition();
            if(fromwhere === "urlFilter"){    //URL字段参数
                //URL暂只支持通过流程名称及流程过滤数据，其它情况使用jsonstr传参
                const supportUrlParams = ["requestname", "workflowid"];
                let newFields = {};
                supportUrlParams.map(k=>{
                    if(k in queryParams)
                        newFields[k] = {name:k, value:`${queryParams[k]}`, dirty:false};
                });
                actions.setFormFields(newFields);
            }else if(fromwhere === "jsonFilter"){   //门户More通过jsonstr传条件
                actions.setSearchUrlParams({jsonstr: queryParams.jsonstr});
            }
        }
        actions.doSearch();
        actions.initTree();
    }
    componentDidMount() {
        _ListenerCtrl.bind();
    }
    componentWillReceiveProps(nextProps) {
        const keyOld = this.props.location.key;
        const keyNew = nextProps.location.key;
    	if(window.location.pathname.indexOf('/spa/workflow/index') >= 0 && nextProps.title && document.title !== nextProps.title)
    		document.title = nextProps.title
        if(keyOld !== keyNew) {
            const {actions} = this.props;
        	this.doInit(nextProps);
            actions.setSelectedTreeKeys();
            actions.setSelectedRowKeys();
        }
    }
    shouldComponentUpdate(nextProps, nextState) {
        return !is(this.props.title, nextProps.title) ||
            !is(this.props.condition, nextProps.condition) ||
            !is(this.props.fields, nextProps.fields)||
            !is(this.props.comsWeaTable,nextProps.comsWeaTable)||
            !is(this.props.showSearchAd,nextProps.showSearchAd)||
            !is(this.props.btninfo, nextProps.btninfo);
    }
    componentWillUnmount() {
        this.props.actions.clearAllState();
        _ListenerCtrl.unbind();
    }
    render() {
        const isSingle = window.location.pathname.indexOf('/spa/workflow/index') >= 0;
        const {loading,comsWeaTable,title,dataKey,actions,showSearchAd,fields} = this.props;
        const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
		const tableNow = comsWeaTable.get(tablekey);
		const loadingTable = tableNow.get('loading');
        const selectedRowKeys = tableNow.get('selectedRowKeys');
        const requestname = fields.hasIn(["requestname", "value"]) ? fields.getIn(["requestname", "value"]) : "";
        return (
            <div className='wea-workflow-query'>
            	{isSingle && <WeaPopoverHrm />}
            	<WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                <WeaTop
                	title={title}
                	loading={loading || loadingTable}
                	icon={<i className='icon-portal-workflow' />}
                	iconBgcolor='#55D2D4'
                	buttons={this.getButtons()}
                	buttonSpace={10}
                	showDropIcon={true}
                	dropMenuDatas={this.getRightMenu()}
                	onDropMenuClick={this.onRightMenuClick.bind(this)}
                >
                    <div style={{height: '100%'}}>
                    	<WeaLeftRightLayout leftCom={this.getTree()} leftWidth={25} >
	                        <WeaTab
	                            onlyShowRight={true}
	                            buttonsAd={this.getTabButtonsAd()}
	                            searchType={['base','advanced']}
	                            searchsBaseValue={requestname}
	                            setShowSearchAd={bool=>{actions.setShowSearchAd(bool)}}
                                hideSearchAd={()=> actions.setShowSearchAd(false)}
	                            searchsAd={<Form horizontal>{this.getSearchs()}</Form>}
	                            showSearchAd={showSearchAd}
	                            onSearch={v=>{actions.doSearch()}}
	                        	onSearchChange={v=>{actions.appendFormFields({requestname:{name:'requestname',value:v}})}}
	                        />
	                        <WeaTable
	                        	sessionkey={dataKey}
		                    	hasOrder={true}
		                    	needScroll={true}
		                    />
	                	</WeaLeftRightLayout>
                    </div>
                </WeaTop>
                </WeaRightMenu>
                <Synergy pathname='/workflow/queryFlow' requestid="-1" />
            </div>
        )
    }
    onRightMenuClick(key){
    }
    getRightMenu(){
    	const { dataKey, comsWeaTable, actions } = this.props;
		const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
		const tableNow = comsWeaTable.get(tablekey);
    	const selectedRowKeys = tableNow.get('selectedRowKeys');
    	let btns = [];
    	btns.push({
            key: "search",
    		icon: <i className='icon-workflow-Right-menu--search'/>,
            content:'搜索',
            onClick: key =>{
                actions.doSearch();
                actions.setShowSearchAd(false);
            }
    	});
        btns.push({
            key:"batchShare",
         	icon: <i className='icon-workflow-Right-menu-Batch-sharing'/>,
			content:'批量共享',
            disabled: !selectedRowKeys || !`${selectedRowKeys.toJS()}`,
            onClick: key =>{
                actions.batchShareWf(`${selectedRowKeys.toJS()}`);
            }
        })
        btns.push({
            key:"colSet",
    		icon: <i className='icon-workflow-Right-menu-Custom'/>,
            content:'显示定制列',
            onClick: key =>{
                actions.setColSetVisible(dataKey,true);
    		    actions.tableColSet(dataKey,true);
            }
    	})
    	return btns
    }
    getSearchs() {
    	const { condition } = this.props;
		let group = [];
		condition.map(v =>{
			let items = [];
			v.get("items").map(item => {
                const fields = item.toJS();
				items.push({
	                com:(<FormItem
                            label={`${fields.label}`}
	                        labelCol={{span: `${fields.labelcol}`}}
	                        wrapperCol={{span: `${fields.fieldcol}`}}>
                        {WeaTools.getComponent(fields.conditionType, fields.browserConditionParam, fields.domkey, this.props, fields)}
	                    </FormItem>),
	                colSpan:1
	            });
			});
			group.push(<WeaSearchGroup needTigger={true} title={v.get("title")} showGroup={v.get("defaultshow")} items={items}/>);
        });
		return group;
    }
    getTree() {
        const {leftTree,actions,selectedTreeKeys} = this.props;
        return (
            <WeaLeftTree
                datas={leftTree && leftTree.toJS()}
                selectedKeys={selectedTreeKeys && selectedTreeKeys.toJS()}
                onFliterAll={()=>{
                	actions.setShowSearchAd(false);
                	actions.setSelectedTreeKeys();
                	actions.clearFormFields();
                    actions.doSearch();
                }}
                onSelect={(key)=>{
                	actions.setShowSearchAd(false);
                	actions.setSelectedTreeKeys([key]);

                	const workflowid = key.indexOf("wf_")===0 ? key.substring(3) : '';
                	const typeid = key.indexOf("type_")===0 ? key.substring(5) : '';
                	let workflowidShowName = '';
                	let typeidShowName = '';
                	leftTree && leftTree.map(l=>{
                		if(l.get('domid') == key) typeidShowName = l.get('name');
                		l.get('childs') && l.get('childs').map(c=>{
                			if(c.get('domid') == key) workflowidShowName = c.get('name');
                		})
                	})
                	const fieldsObj = {
                		workflowid:{name:'workflowid',value:workflowid,valueSpan:workflowidShowName},
                		typeid:{name:'typeid',value:typeid,valueSpan:typeidShowName},
                	};
                	actions.setFormFields(fieldsObj);
                    actions.doSearch();
                }} />
        )
    }
    getTabButtonsAd() {
        const {actions} = this.props;
        return [
            (<Button type="primary" onClick={()=>{actions.doSearch();actions.setShowSearchAd(false)}}>搜索</Button>),
            (<Button type="ghost" onClick={()=>{actions.clearFormFields();actions.setSelectedTreeKeys();}}>重置</Button>),
            (<Button type="ghost" onClick={()=>{actions.setShowSearchAd(false)}}>取消</Button>)
        ]
    }
    getButtons() {
        const { dataKey, comsWeaTable, actions } = this.props;
		const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
		const tableNow = comsWeaTable.get(tablekey);
    	const selectedRowKeys = tableNow.get('selectedRowKeys');
        let btns =[];
        btns.push(<Button type="primary" disabled={!(selectedRowKeys && `${selectedRowKeys.toJS()}`)} onClick={()=>{actions.batchShareWf(`${selectedRowKeys.toJS()}`)}}  >批量共享</Button>);
        return btns
    }
}

class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

QueryFlowResult = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(QueryFlowResult);

QueryFlowResult = createForm({
    onFieldsChange(props, changeFields) {
        props.actions.appendFormFields(changeFields);
    },
    mapPropsToFields(props) {
        return props.fields.toJS();
    }
})(QueryFlowResult);

function mapStateToProps(state) {
    const {workflowqueryFlow,comsWeaTable} = state;
    return {
    	loading: workflowqueryFlow.get('loading'),
        title: workflowqueryFlow.get('title'),
        condition: workflowqueryFlow.get('condition'),
        fields: workflowqueryFlow.get('fields'),
        dataKey: workflowqueryFlow.get('dataKey'),
        showSearchAd: workflowqueryFlow.get('showSearchAd'),
        leftTree: workflowqueryFlow.get('leftTree'),
        selectedTreeKeys:workflowqueryFlow.get('selectedTreeKeys'),
        //table
        comsWeaTable, //绑定整个table
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...QueryFlowAction,setNowRouterWfpath,...WeaTableAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(QueryFlowResult);